package com.bw.controller;

import com.bw.entity.User;
import com.bw.mapper.UserMapper;
import org.spring.kun.common.Md5Utils;
import org.spring.kun.common.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

@Controller
public class LoginController {

    @Autowired
    UserMapper userMapper;

    @RequestMapping("/loginPage.do")
    public String loginPage(){
        return "login";
    }

    @RequestMapping("/login.do")
    public String login(@Valid User loginUser, BindingResult result, Model model, HttpServletResponse response, HttpServletRequest request){
        if (result.hasErrors()){
            model.addAttribute("error",result.getAllErrors().get(0).getDefaultMessage());
            return "login";
        }
        User userDB =   userMapper.selectByName(loginUser.getName());
        if (userDB == null){
            model.addAttribute("error","用户不存在");
            return "login";
        }
        String loginUserPassword = loginUser.getPassword();// 用户输入的密码
        String password = userDB.getPassword();
        String salt = userDB.getSalt();

        String md5String = Md5Utils.getMD5String(loginUserPassword + salt);

        if (!md5String.equals(password)){
            model.addAttribute("error","密码错误");
            return "login";
        }

        // 加密用户信息 得到令牌token   把token放入cookie    把cookie返回给浏览器
        TokenUtils.responseTokenByCookie(userDB,response);
        return "redirect:list.do";
    }

    @RequestMapping("/list.do")
    public String list(HttpServletRequest request,Model model){

        // 获取当前登录用户
        User userFromRequest = TokenUtils.getLoginUserFromRequest(request, User.class);

        model.addAttribute("name",userFromRequest.getName());
        model.addAttribute("nickName",userFromRequest.getNickName());
        model.addAttribute("avatarUrl",userFromRequest.getAvatarUrl());
        return "list";
    }
}
